package ilincar.systemcore.sim;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import com.google.gson.Gson;
import com.ilincar.utils.IlincarUrls;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import ilincar.entity.SimEntity;
import ilincar.systemcore.App;
import ilincar.systemcore.net.IlincarRequest;
import ilincar.systemcore.net.IlincarUtils;
import ilincar.systemcore.tool.ILog;

/**
 * SIM卡的管理，包含，上传当前SIM 卡信息
 * SIM卡重新插拨后，检测SIM卡信息，和上次是否一样,如果不一样，重新上传
 * Created by ilincar on 2016/12/12.
 */

public class SimManager {

    private final String TAG = "SimManager";

    private Context mContext;

    private IntentFilter mIntentFilter = null;

    private final String ACTION_SIM_STATE_CHANGED = "android.intent.action.SIM_STATE_CHANGED";

    private TelephonyManager mTelephonyManager = null;

    private boolean mIsSimCardLicit = false;

    private SimEntity mSimEntity = null;

    private String mSimCardICCID;

    private App mApp;

    public SimManager(Context context) {
        this.mContext = context;
        mApp = (App)mContext.getApplicationContext();

        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(ACTION_SIM_STATE_CHANGED);
        mIntentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        mContext.registerReceiver(mReceiver, mIntentFilter);

        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        mSimCardICCID = mTelephonyManager.getSimSerialNumber();
        checkSimValidity();
    }

    /**
     * 检查SIM卡是否合法
     */
    private void checkSimValidity() {
        //如果SIM已经插入，并且有网络
        ILog.d(TAG, "检查 SIM 卡信息......");
        if (mTelephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY && IlincarUtils.hasNetwork(mContext)) {
            String iccid = IlincarUtils.getICCID(mContext);
            if (iccid != null && (!iccid.equals(""))) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("simIccid", IlincarUtils.getICCID(mContext));
                    jsonObject.put("deviceId", IlincarUtils.getIntMacByShell());

                    mApp.getRequest().postToServer(IlincarUrls.SIMCARD_VALIDITY_URL, jsonObject, new IlincarRequest.RequestCallBack(){
                        @Override
                        public void onFailure(IOException e) {
                            ILog.d(TAG, "检查SIM卡信息发生异常 : " + e.getMessage());
                        }

                        @Override
                        public void onResponse(String result) {
                            ILog.d(TAG, "检查SIM卡信息 : " + result);
                            Gson gson = new Gson();
                            mSimEntity = gson.fromJson(result, SimEntity.class);
                            if(mSimEntity.getResultCode().equals("00")){
                                mIsSimCardLicit = true;
                            }else {
                                mIsSimCardLicit = false;
                            }
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public SimEntity getSimEntity() {
        return mSimEntity;
    }

    public boolean isSimCardLicit() {
        return mIsSimCardLicit;
    }

    public void stop() {
        mContext.unregisterReceiver(mReceiver);
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_SIM_STATE_CHANGED)) {
                //SIM卡状态发生改变
                if(mTelephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY){
                    checkSimValidity();
                }
            } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
                //飞行模式
                try {
                    int modeState = Settings.System.getInt(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON);
                } catch (Settings.SettingNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }
    };
}
